﻿using System;
using Vbyte.SharpOrm.SqlDb;

namespace Vbyte.SharpOrm.Config
{
    /// <summary>
    /// SQL数据库外键属性设置
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
    public class ForeignKeyAttribute : Attribute, ISqlConstraintExpBuild
    {
        /// <summary>
        /// 设置关系表中的外键约束
        /// </summary>
        /// <param name="tableName">外键表名称</param>
        /// <param name="colName">外键表中的列名称</param>
        public ForeignKeyAttribute(string tableName, string colName)
        {
            ForeignKeyTable = tableName;
            ForeginKeyColumn = colName;
        }

        /// <summary>
        /// 设置关系表中的外键约束(同列名)
        /// </summary>
        /// <param name="tabName">外键表名称</param>
        public ForeignKeyAttribute(string tabName)
            : this(tabName, null)
        {

        }

        /// <summary>
        /// 外键表名称
        /// </summary>
        public string ForeignKeyTable { get; set; }

        /// <summary>
        /// 外键表中的列名称
        /// </summary>
        public string ForeginKeyColumn { get; set; }

        #region ISqlConstraintExpBuild 成员

        /// <summary>
        /// 获取SQL约束的表达式语句
        /// </summary>
        /// <param name="dbOwner">数据库所有者占位前缀</param>
        /// <param name="tableName">数据库表名</param>
        /// <param name="columnName">涉及到的列名</param>
        /// <returns>SQL约束表达式的中间语句</returns>
        public string GetExpression(string dbOwner, string tableName, string columnName)
        {
            return string.Format("FOREIGN KEY ({0}) REFERENCES {1}{2} ( {3} ) ON UPDATE CASCADE ON DELETE CASCADE",
                            columnName,
                            dbOwner,
                            ForeignKeyTable,
                            ForeginKeyColumn);
        }

        #endregion
    }

}
